package chat

import (
	"crypto/md5"
	"fmt"
	"io"
	"net"
	"os"
)

func getFileInfo(filename string) *SysFileInfo {
	fi, err := os.Lstat(filename)
	if err != nil {
		fmt.Println("info ERROR", err)
		return nil
	}
	fileHandle, err := os.Open(filename)
	if err != nil {
		fmt.Println("open ERROR", err)
		return nil
	}

	h := md5.New()
	_, err = io.Copy(h, fileHandle)
	fileInfo := &SysFileInfo{
		fName:  fi.Name(),
		fSize:  fi.Size(),
		fPerm:  fi.Mode().Perm(),
		fMtime: fi.ModTime(),
		fType:  fi.IsDir(),
		fMd5:   fmt.Sprintf("%x", h.Sum(nil)),
	}
	return fileInfo
}

func Send(files string, destination string) {
	fInfo := getFileInfo(files)
	newName := fmt.Sprintf("%s", fInfo.fName)
	cmdLine := fmt.Sprintf("upload %s %d %d %d %s ", newName, fInfo.fMtime.Unix(), fInfo.fPerm, fInfo.fSize, fInfo.fMd5)
	cn, err := net.Dial("tcp", destination)
	if err != nil {
		fmt.Println("connect error", err)
		return
	}
	defer cn.Close()
	cn.Write([]byte(cmdLine))
	cn.Write([]byte("\r\n"))
	fileHandle, err := os.Open(files)
	if err != nil {
		fmt.Println("open ERROR", err)
		return
	}
	fmt.Println("开始传输文件 " + files)
	io.Copy(cn, fileHandle)
	for {
		buffer := make([]byte, 1024)
		num, err := cn.Read(buffer)
		if err == nil && num > 0 {
			//fmt.Println(string(buffer[:num]))
			break
		}
	}
}

//该代码片段来自于: http://www.sharejs.com/codes/go/5640
